<?php

namespace app\batch;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Debug;
use app\models\{Order, Business, Agent, AgentArea, Config, OrderGoods, Goods, GoodsSpec};
use think\Db;
use think\facade\Log;
use app\facade\Redis;

class OrderIncome extends Command
{
    protected $open = false;
    protected function configure()
    {
        $this->setName('OrderIncome')->setDescription('订单结算');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        ini_set('max_execution_time', 0);
        $config = (new Config())->where('name', 'rate')->value('value');
        $config = json_decode($config, true);
        if (empty($config)) {
            $config = [
                'allrate' => 10, //总共抽取百分比点数
                'arearate' => 0, //区域代理收取百分比点数
                'cityrate' => 0, //城市代理收取百分比点数
                'streetrate' => 0,
            ];
        }
        // (new Order())->where(['status' => [2, 3], 'isagent' => 1])->chunk(10, function ($lists) use ($config) {
        //     foreach ($lists as $list) {
        //         $frtimes = Redis::get('orderincome' . $list['id']);
        //         if ($frtimes) {
        //             continue;
        //         } else {
        //             Redis::setex('orderincome' . $list['id'], 5, 5);
        //         }
        //         //查找街道代理级别
        //         $agentstreet = (new AgentArea())->where(['type' => 4, 'street' => $list['street']])->value('agentid') ?? 0;
        //         //查找区域代理级别
        //         $agentarea = (new AgentArea())->where(['type' => 3, 'area' => $list['area']])->value('agentid') ?? 0;
        //         //查找城市代理
        //         $agentcity = (new AgentArea())->where(['type' => 2, 'city' => $list['city']])->value('agentid') ?? 0;
        //         //计算各级收益
        //         $business_money = floor($list['total'] * (100 - $config['allrate'])) / 100;
        //         //街道代理收益
        //         $street_money = floor($list['total'] * $config['streetrate']) / 100;
        //         //区域代理收益
        //         $area_money = floor($list['total'] * $config['arearate']) / 100;
        //         //城市代理收益
        //         $city_money = floor($list['total'] * $config['cityrate']) / 100;
        //         //没有街道代理
        //         if ($agentstreet <= 0) {
        //             $area_money =  $area_money + $street_money;
        //             $street_money = 0;
        //         }
        //         //没有区域代理
        //         if ($agentarea <= 0) {
        //             $city_money =  $city_money + $area_money;
        //             $area_money = 0;
        //         }
        //         //没有城市代理
        //         if ($agentcity <= 0) {
        //             $city_money =  0;
        //         }
        //         $parms = [
        //             'agentstreet' => $agentstreet,
        //             'agentarea' => $agentarea,
        //             'agentcity' => $agentcity,
        //             'config' => $config,
        //             'businessmoney' => $business_money,
        //             'area_money' => $area_money,
        //             'city_money' => $city_money,
        //             'pingtai' => $list['total'] - $business_money - $area_money - $city_money - $street_money
        //         ];
        //         $goodsids = [];
        //         $goodsspecids = [];
        //         $goodslist = (new OrderGoods())->where('ordersn', $list['ordersn'])->select();
        //         foreach ($goodslist as $goodslists) {
        //             $goodsids[] = $goodslists['goodsid'];
        //             $goodsspecids[] = $goodslists['goodspecid'];
        //         }
        //         Db::startTrans();
        //         try {
        //             (new Order())->where('id', $list['id'])->update(['cityid' => $agentcity, 'areaid' => $agentarea, 'streetid' => $agentstreet, 'isagent' => 2, 'incomeparms' => json_encode($parms, true), 'money' => $business_money]);
        //             Db::commit();
        //         } catch (\Exception $e) {
        //             Db::rollback();
        //             echo $e->getMessage();
        //             continue;
        //         }
        //         echo '结算成功';
        //     }
        // });
        (new Order())->where(['status' => 4, 'incomestatus' => 1])->chunk(10, function ($lists) use ($config) {
            foreach ($lists as $list) {
                $frtimes = Redis::get('orderincome' . $list['id']);
                if ($frtimes) {
                    continue;
                } else {
                    Redis::setex('orderincome' . $list['id'], 5, 5);
                }
                //查找街道代理级别
                $agentstreet = (new AgentArea())->where(['type' => 4, 'street' => $list['street']])->value('agentid') ?? 0;
                //查找区域代理级别
                $agentarea = (new AgentArea())->where(['type' => 3, 'area' => $list['area']])->value('agentid') ?? 0;
                //查找城市代理
                $agentcity = (new AgentArea())->where(['type' => 2, 'city' => $list['city']])->value('agentid') ?? 0;
                //计算各级收益
                $business_money = floor($list['total'] * (100 - $config['allrate'])) / 100;
                //街道代理收益
                $street_money = floor($list['total'] * $config['streetrate']) / 100;
                //区域代理收益
                $area_money = floor($list['total'] * $config['arearate']) / 100;
                //城市代理收益
                $city_money = floor($list['total'] * $config['cityrate']) / 100;
                //没有街道代理
                if ($agentstreet <= 0) {
                    $area_money =  $area_money + $street_money;
                    $street_money = 0;
                }
                //没有区域代理
                if ($agentarea <= 0) {
                    $city_money =  $city_money + $area_money;
                    $area_money = 0;
                }
                //没有城市代理
                if ($agentcity <= 0) {
                    $city_money =  0;
                }
                $parms = [
                    'agentstreet' => $agentstreet,
                    'agentarea' => $agentarea,
                    'agentcity' => $agentcity,
                    'config' => $config,
                    'businessmoney' => $business_money,
                    'street_money' => $area_money,
                    'area_money' => $area_money,
                    'city_money' => $city_money,
                    'pingtai' => floor(($list['total'] - $business_money - $area_money - $city_money - $street_money)*100)/100
                ];
                $goodsids = [];
                $goodsspecids = [];
                $goodslist = (new OrderGoods())->where('ordersn', $list['ordersn'])->select();
                foreach ($goodslist as $goodslists) {
                    $goodsids[] = $goodslists['goodsid'];
                    $goodsspecids[] = $goodslists['goodspecid'];
                }
                if (($business_money + $street_money + $area_money + $city_money) > $list['total']) {
                    echo '结算金额超过订单金额';
                    continue;
                }
                Db::startTrans();
                try {
                    (new Goods())->where(['id' => $goodsids])->setInc('sale');
                    (new GoodsSpec())->where(['id' => $goodsspecids])->setInc('sales');
                    (new Order())->where('id', $list['id'])->update(['cityid' => $agentcity, 'areaid' => $agentarea, 'streetid' => $agentstreet, 'incomestatus' => 2, 'incomeparms' => json_encode($parms, true), 'money' => $business_money]);
                    if ($list['payment'] == 1 || $list['payment'] == 3) {
                        (new Business())->MoneyEdit($list['businessid'], 1, $business_money, '订单结算', $list['ordersn']);
                        (new Agent())->MoneyEdit($agentstreet, 4, $street_money, '社区代理收益', $list['ordersn'], $list['businessid']);
                        (new Agent())->MoneyEdit($agentarea, 2, $area_money, '区代收益', $list['ordersn'], $list['businessid']);
                        (new Agent())->MoneyEdit($agentcity, 1, $city_money, '市代收益', $list['ordersn'], $list['businessid']);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    echo $e->getMessage();
                    continue;
                }
                echo '结算成功';
            }
        });
    }
}
